package com.myMinistry.gui;

import java.util.ArrayList;

import android.os.Bundle;
import android.support.v4.app.ListFragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListView;

import com.myMinistry.R;
import com.myMinistry.gui.TimeEditor.LitEntry;

public class PlacedLiteratureListFrag extends ListFragment {
	private final ArrayList<LitEntry> list = new ArrayList<LitEntry>();
	private ArrayAdapter<LitEntry> adapter;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
    	super.onCreate(savedInstanceState);
	}
	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, 
	        Bundle savedInstanceState) {
			View view = inflater.inflate(R.layout.list_fragment, null);
			return view;
	}
    
    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
    	super.onActivityCreated(savedInstanceState);
    	adapter = new ArrayAdapter<LitEntry>(getActivity().getApplicationContext()
    			,R.layout.literature_listview_item
    			,list
    			);
    	setListAdapter(adapter);
    }
    
    @Override
	public void onListItemClick(ListView l, View v, int position, long id) {
		if(getActivity() instanceof TimeEditor) {
			LitEntry entry = (LitEntry) l.getItemAtPosition(position);
			((TimeEditor) getActivity()).changeLitEntry(position, entry.getLitName());
		}
    }
	
	public void addEntry(LitEntry entry) {
		list.add(entry);
		adapter.notifyDataSetChanged();
		sendArrayToActivity();
	}
	
	public void updateEntry(LitEntry entry, int which) {
		list.remove(which);
		list.add(which, entry);
		adapter.notifyDataSetChanged();
		sendArrayToActivity();
	}
	
	public void removeEntry(int which) {
    	list.remove(which);
		adapter.notifyDataSetChanged();
		sendArrayToActivity();
	}
	
	public void populateList(ArrayList<LitEntry> thisList) {
		for(LitEntry thisEntry : thisList)
			list.add(thisEntry);
		adapter.notifyDataSetChanged();
	}
	
	private void sendArrayToActivity() {
		if(getActivity() instanceof TimeEditor)
			((TimeEditor) getActivity()).sendArrayToActivity(list);
	}
}